// service/user_service/user_update.go
package user_service

import (
	"errors"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/ref"
)

type UserUpdateRequest struct {
	Nickname *string `json:"nickname"`
	Avatar   *string `json:"avatar"`
	Role     *int8   `json:"role"`
	Scope    *int    `json:"scope"`
}

func (UserService) UserUpdate(userID uint, req UserUpdateRequest) (user models.UserModel, err error) {
	err = global.DB.Take(&user, userID).Error
	if err != nil {
		err = errors.New("用户不存在")
		return
	}

	maps, err := ref.StructToMap(req)
	//同时修改用户名
	if req.Nickname != nil {
		var exists bool
		result := global.DB.Model(&user).Select("1").Where("nickname = ?", req.Nickname).Limit(1).Find(&exists)
		if result.RowsAffected > 0 {
			// Nickname 存在
			err = errors.New("昵称已经存在请重新输入")
			return
		}
		maps["username"] = *req.Nickname
	}
	if err != nil {
		return
	}
	if len(maps) > 0 {
		err = global.DB.Model(&user).Updates(maps).Error
		if err != nil {
			return
		}
	}
	return
}
